import { defineStore } from 'pinia'
import { store } from '/@/store'
import coreTool from '/@/tool/coreTool'
import type { AxiosResponse } from 'axios'
import type { Res } from '/@/tool/Res'
import type { Param } from '/@/tool/Param'

import coreToolService from '/@/api/cn/core/tool/coreToolService'

import type { LoginAO } from '/@/model/cn/core/tool/ao/LoginAO'
import type { LoginVO } from '/@/model/cn/core/tool/vo/LoginVO'

interface CoreToolState {
  switchPostLoginInfo: object
  allDictValueMapInfo: object
  fileUrlPrefix: string
}

export const useCoreToolStore = defineStore({
  id: 'coreTool',
  state: (): CoreToolState => ({
    switchPostLoginInfo: {},
    allDictValueMapInfo: {},
    fileUrlPrefix: 'http://localhost',
  }),
  getters: {
    getDictDisplayName: (state) => (dictKey: string, value: string): string => {
      return state.allDictValueMapInfo![dictKey] ? state.allDictValueMapInfo![dictKey][value] as string || value : value
    },
    getFileFullUrl: (state) => (fileUrl: string): string => {
      return `${state.fileUrlPrefix}${fileUrl}`
    },
  },
  actions: {
    setSwitchPostLoginInfo(value?: object): void {
      typeof value === 'undefined' ? this.switchPostLoginInfo = coreTool.ls.get!('switchPostLoginInfo') ? coreTool.ls.get!('switchPostLoginInfo') as object : {} : this.switchPostLoginInfo = value
    },
    setAllDictValueMapInfo(value?: object): void {
      typeof value === 'undefined' ? this.allDictValueMapInfo = coreTool.ls.get!('allDictValueMapInfo') ? coreTool.ls.get!('allDictValueMapInfo') as object : {} : this.allDictValueMapInfo = value
    },
    setFileUrlPrefix(value?: string): void {
      typeof value === 'undefined' ? this.fileUrlPrefix = coreTool.ls.get!('fileUrlPrefix') ? coreTool.ls.get!('fileUrlPrefix') as string : 'http://localhost' : this.fileUrlPrefix = value
    },
    login(param: Param<LoginAO>): Promise<Res<LoginVO>> {
      return new Promise<Res<LoginVO>>((resolve, reject) => {
        coreToolService.login(param).then((res: AxiosResponse<Res<LoginVO>>) => {
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },
  },
})

export function useCoreToolStoreWithout() {
  return useCoreToolStore(store)
}
